package com.spzx.product.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.utils.poi.ExcelUtil;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.log.annotation.Log;
import com.spzx.common.log.enums.BusinessType;
import com.spzx.common.security.annotation.InnerAuth;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.common.security.annotation.RequiresPermissions;
import com.spzx.product.api.domain.vo.CategoryTreeVo;
import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.domain.Category;
import com.spzx.product.domain.vo.CategoryExcelVo;
import com.spzx.product.listener.ExcelListener;
import com.spzx.product.service.ICategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 商est 前端控制器
 * </p>
 *
 * @author lee
 * @since 2024-07-13
 */
@Tag(name = "商品分类接口管理")
@RestController
@RequestMapping("/category")
@RequiresLogin
public class CategoryController extends BaseController {
    @Autowired
    private ICategoryService categoryService;

    @InnerAuth
    @Operation(summary = "分类树")
    @GetMapping("/tree")
    public R<List<CategoryTreeVo>> getCategoryTree(){
        List<CategoryTreeVo> categoryTreeVoList = categoryService.getCategoryTree();
        return R.ok(categoryTreeVoList);
    }

    @InnerAuth
    @Operation(summary = "获取一级分类")
    @GetMapping("/getOneCategory")
    public R<List<CategoryVo>> getOneCategory(){
        List<CategoryVo> oneCategory = categoryService.getOneCategory();
        return R.ok(oneCategory);
    }

    @Operation(summary = "获取分类下拉树列表")
    @GetMapping("/treeSelect/{id}")
    public AjaxResult treeSelect(@PathVariable("id") Integer id) {
        return success(categoryService.treeSelect(id));
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<Category> util = new ExcelUtil<>(Category.class);
        util.importTemplateExcel(response, "商品分类数据");
    }

    /**
     *若依的方式实现文件导出
     */
//    @PostMapping("/export")
//    public void export(HttpServletResponse response)
//    {
//        List<Category> list = categoryService.list();
//        ExcelUtil<Category> util = new ExcelUtil<>(Category.class);
//        util.exportExcel(response, list, "商品分类数据");
//    }


    /**
     * EasyExcel的方式实现文件导出
     */
    @PostMapping("/export")
    @Log(title = "分类", businessType = BusinessType.EXPORT)
    @RequiresPermissions("product:category:export")
    public void download(HttpServletResponse response) throws IOException {
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //要写入excel中的数据
            List<CategoryExcelVo> list = categoryService.list().stream().map(category -> {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo);
                categoryExcelVo.setStatus(category.getStatus() == 1 ? "显示" : "不显示");
                return categoryExcelVo;
            }).collect(Collectors.toList());
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("模板").doWrite(list);
        } catch (IOException e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 若依的方式实现文件导入
     */
//    @PostMapping("/importData")
//    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
//        ExcelUtil<Category> util = new ExcelUtil<>(Category.class);
//        List<Category> categoryList = util.importExcel(file.getInputStream());
//        String operName = SecurityUtils.getUsername();
//        String message = categoryService.importCategory(categoryList, updateSupport, operName);
//        return success(message);
//
//    }
    @PostMapping("/importData")
    @Log(title = "分类", businessType = BusinessType.IMPORT)
    @RequiresPermissions("product:category:import")
    public AjaxResult upload(MultipartFile file, boolean updateSupport) throws IOException {
        ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>();
        EasyExcel.read(file.getInputStream(), CategoryExcelVo.class, excelListener).sheet().doRead();
        List<CategoryExcelVo> datas = excelListener.getDatas();
        if (!CollectionUtils.isEmpty(datas)) {
            ArrayList<Category> categoryList = new ArrayList<>(datas.size());
            for (CategoryExcelVo data : datas) {
                Category category = new Category();
                BeanUtils.copyProperties(data, category);
                category.setStatus("显示".equals(data.getStatus()) ? 1 : 0);
                categoryList.add(category);
            }
            if (updateSupport) {
                categoryService.saveOrUpdateBatch(categoryList);
            }
            if (!updateSupport) {
                categoryService.saveBatch(categoryList);
            }

        }
        return success();

    }
}
